/**
 * 
 */
package com.bolbachchan.blog.dao.security;

import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;

/**
 * @author Chaitanya
 * 
 */
public class LdapSecurityDAOImpl implements LdapSecurityDAO {

	@Autowired
	private LdapTemplate ldapTemplate;

	public void setLdapTemplate(LdapTemplate ldapTemplate) {
		this.ldapTemplate = ldapTemplate;
	}

	@SuppressWarnings("unchecked")
	public List<String> findUsername(String username) {
		List<String> usernames = null;
		StringBuilder searchFilter = new StringBuilder();
		searchFilter.append(UID).append(username).append(",");
		searchFilter.append(ORGAINZATIONAL_UNIT);

		try {
			usernames = ldapTemplate.search(searchFilter.toString(),
					PERSON_OBJECTCLASS, new AttributesMapper() {
						@Override
						public Object mapFromAttributes(Attributes attrs)
								throws NamingException {
							return attrs.get(USER_ID).get();
						}
					});
		} catch (NameNotFoundException nnfe) {
			return usernames;
		}
		return usernames;
	}
}
